package com.reactim.message.protection;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.time.Instant;

/**
 * 连接行为记录
 */
@Data
@AllArgsConstructor
public class ConnectionBehavior {
    
    /**
     * 用户ID
     */
    private final Long userId;
    
    /**
     * 客户端IP
     */
    private final String clientIp;
    
    /**
     * 连接建立时间
     */
    private final Instant connectedAt;
    
    /**
     * 最后活跃时间
     */
    private volatile Instant lastActiveTime;
    
    /**
     * 请求计数
     */
    private volatile long requestCount;
    
    public ConnectionBehavior(Long userId, String clientIp, Instant connectedAt) {
        this.userId = userId;
        this.clientIp = clientIp;
        this.connectedAt = connectedAt;
        this.lastActiveTime = connectedAt;
        this.requestCount = 0;
    }
    
    /**
     * 记录活跃时间
     */
    public void recordActivity() {
        this.lastActiveTime = Instant.now();
        this.requestCount++;
    }
    
    /**
     * 获取连接持续时间（秒）
     */
    public long getConnectionDurationSeconds() {
        return java.time.Duration.between(connectedAt, Instant.now()).getSeconds();
    }
    
    /**
     * 获取平均请求频率（每分钟）
     */
    public double getAverageRequestRate() {
        long durationMinutes = java.time.Duration.between(connectedAt, Instant.now()).toMinutes();
        if (durationMinutes == 0) {
            return requestCount;
        }
        return (double) requestCount / durationMinutes;
    }
}